<?php
namespace app\common\model;

use think\Db;
use think\Model;

/**
 * 优惠券模型
 */
class CouponModel extends Model
{
    protected $name = 'coupon';


    /**
     * 领券中心--获取可领取优惠券
     *
     * @param $user_id int 用户ID
     * @param $use_type string 使用位置:mini=小程序,pc=PC
     * @param $page int 页码
     * @param $limit int 每页数据
     */
    public function getCouponPageList($params,$user_id,$page,$limit)
    {
        extract($params);
        try {
            // 获取用户已领取的优惠券ids
            $coupon_ids = model('app\common\model\UserCouponModel')->where(['user_id' => $user_id])->column('coupon_id');

            $field = ['id','discount_type','goods_type','use_type','title','target','price','discount','sent_num','draw_num','starttime','endtime'];
            $time = time();
            $where = [
                'id' => ['not in', $coupon_ids],
//                'starttime' => ['<=', $time],
                'endtime' => ['>=', $time]
            ];
            $list = self::field($field)
                ->where($where)
                ->whereRaw('sent_num - draw_num > 0')
                ->order('weigh', 'asc')
                ->paginate($limit, false, ['page' => $page]);
            $discount_type = [1 => '满减', 2 => '折扣'];
            $goods_type = ['all' => '全部商品', 'part' => '部分商品'];
            $use_type = ['mini' => '小程序', 'pc' => 'PC'];

            foreach ($list as $row){
                $row->discount_type_text = $discount_type[$row->discount_type];
                $row->goods_type_text = $goods_type[$row->goods_type];
//                $row->use_type_text = $use_type[$row->use_type];
                $row->starttime = datetime($row->starttime);
                $row->endtime = datetime($row->endtime);
                $row->is_draw = in_array($row->id,$coupon_ids)?1:0;
            }
            return [
                'code' => 200,
                'msg' => '请求成功',
                'data' => $list
            ];
        }catch (\Exception $e) {
            return [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'data' => []
            ];
        }
    }

    /**
     * 领券中心--领取优惠券
     *
     * @param $user_id int 用户ID
     * @param $coupon_id int 优惠券ID
     */
    public function drawCoupon($params,$user_id)
    {
        extract($params);

        Db::startTrans();
        try {
            $couponInfo = $this->get($coupon_id);
            if(!$couponInfo){
                throw new \Exception('系统错误, 优惠券不存在',41001);
            }

            if($couponInfo->sent_num - $couponInfo->draw_num < 0){
                throw new \Exception('领取失败, 优惠券已领完',41002);
            }

            $user_coupon = model('app\common\model\UserCouponModel')->get(['user_id' => $user_id,'coupon_id' => $coupon_id]);
            if($user_coupon){
                throw new \Exception('优惠券已领取, 请勿重复操作',41003);
            }

            $couponInfo->sent_num += 1;
            $couponInfo->save();

            model('app\common\model\UserCouponModel')->create([
                'user_id' => $user_id,
                'coupon_id' => $couponInfo->id,
                'discount_type' => $couponInfo->discount_type,
                'goods_type' => $couponInfo->goods_type,
                'goods_ids' => $couponInfo->goods_ids,
                'use_type' => $couponInfo->use_type,
                'starttime' => $couponInfo->starttime,
                'endtime' => $couponInfo->endtime,
                'status' => 1,
                'title' => $couponInfo->title,
                'createtime' => time(),
                'image' => $couponInfo->image,
                'target' => $couponInfo->target,
                'price' => $couponInfo->price,
                'discount' => $couponInfo->discount,
            ]);

            Db::commit();
            return [
                'code' => 200,
                'msg' => '请求成功',
                'data' => []
            ];
        }catch (\Exception $e) {
            Db::rollback();
            return [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'data' => []
            ];
        }
    }

}